import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

/**
 * 权限校验中间件
 */
export class PermissionMiddleware {
  constructor() {
    this.userStore = useUserStore()
  }

  /**
   * 检查页面访问权限
   * @param {Object} route - 路由对象
   * @returns {boolean} 是否有权限
   */
  checkPagePermission(route) {
    if (!route.meta || !route.meta.roles) {
      return true
    }

    const userRoles = this.userStore.roles
    return route.meta.roles.some(role => userRoles.includes(role))
  }

  /**
   * 检查按钮权限
   * @param {string|Array} permissions - 权限码或权限码数组
   * @returns {boolean} 是否有权限
   */
  checkButtonPermission(permissions) {
    const userPermissions = this.userStore.permissions
    
    // 超级管理员拥有所有权限
    if (userPermissions.includes('*:*:*')) {
      return true
    }

    if (typeof permissions === 'string') {
      return userPermissions.includes(permissions)
    }

    if (Array.isArray(permissions)) {
      return permissions.some(permission => userPermissions.includes(permission))
    }

    return false
  }

  /**
   * 检查角色权限
   * @param {string|Array} roles - 角色或角色数组
   * @returns {boolean} 是否有权限
   */
  checkRolePermission(roles) {
    const userRoles = this.userStore.roles

    if (typeof roles === 'string') {
      return userRoles.includes(roles)
    }

    if (Array.isArray(roles)) {
      return roles.some(role => userRoles.includes(role))
    }

    return false
  }

  /**
   * 检查API权限
   * @param {string} url - API地址
   * @param {string} method - 请求方法
   * @returns {boolean} 是否有权限
   */
  checkApiPermission(url, method = 'GET') {
    const userPermissions = this.userStore.permissions
    
    // 超级管理员拥有所有权限
    if (userPermissions.includes('*:*:*')) {
      return true
    }

    // 构建权限码：模块:操作:资源
    const permissionCode = this.buildPermissionCode(url, method)
    return userPermissions.includes(permissionCode)
  }

  /**
   * 构建权限码
   * @param {string} url - API地址
   * @param {string} method - 请求方法
   * @returns {string} 权限码
   */
  buildPermissionCode(url, method) {
    // 简化的权限码构建逻辑
    const pathSegments = url.split('/').filter(segment => segment && segment !== 'api')
    
    if (pathSegments.length >= 2) {
      const module = pathSegments[0]
      const resource = pathSegments[1]
      const operation = this.getOperationByMethod(method)
      
      return `${module}:${resource}:${operation}`
    }

    return url
  }

  /**
   * 根据HTTP方法获取操作类型
   * @param {string} method - HTTP方法
   * @returns {string} 操作类型
   */
  getOperationByMethod(method) {
    const methodMap = {
      'GET': 'view',
      'POST': 'add',
      'PUT': 'edit',
      'DELETE': 'delete',
      'PATCH': 'update'
    }
    
    return methodMap[method.toUpperCase()] || 'view'
  }

  /**
   * 权限拦截器
   * @param {Function} handler - 处理函数
   * @param {Object} options - 选项
   * @returns {Function} 拦截后的函数
   */
  withPermission(handler, options = {}) {
    return async (...args) => {
      const { 
        roles, 
        permissions, 
        onDenied = () => ElMessage.error('权限不足'),
        silent = false 
      } = options

      let hasPermission = true

      // 检查角色权限
      if (roles && !this.checkRolePermission(roles)) {
        hasPermission = false
      }

      // 检查按钮权限
      if (permissions && !this.checkButtonPermission(permissions)) {
        hasPermission = false
      }

      if (!hasPermission) {
        if (!silent) {
          onDenied()
        }
        return Promise.reject(new Error('权限不足'))
      }

      return handler.apply(this, args)
    }
  }

  /**
   * 批量权限检查
   * @param {Array} checks - 权限检查配置数组
   * @returns {Object} 权限检查结果
   */
  batchCheck(checks) {
    const results = {}

    checks.forEach(check => {
      const { key, type, value } = check
      
      switch (type) {
        case 'role':
          results[key] = this.checkRolePermission(value)
          break
        case 'permission':
          results[key] = this.checkButtonPermission(value)
          break
        case 'api':
          results[key] = this.checkApiPermission(value.url, value.method)
          break
        default:
          results[key] = false
      }
    })

    return results
  }
}

// 创建全局权限中间件实例
export const permissionMiddleware = new PermissionMiddleware()

/**
 * 权限检查装饰器
 * @param {Object} options - 权限选项
 * @returns {Function} 装饰器函数
 */
export function requirePermission(options) {
  return function(target, propertyKey, descriptor) {
    const originalMethod = descriptor.value

    descriptor.value = function(...args) {
      const middleware = new PermissionMiddleware()
      return middleware.withPermission(originalMethod, options).apply(this, args)
    }

    return descriptor
  }
}

/**
 * 权限校验组合式函数
 * @returns {Object} 权限校验方法
 */
export function usePermission() {
  const middleware = new PermissionMiddleware()

  return {
    hasRole: middleware.checkRolePermission.bind(middleware),
    hasPermission: middleware.checkButtonPermission.bind(middleware),
    hasApiPermission: middleware.checkApiPermission.bind(middleware),
    checkPage: middleware.checkPagePermission.bind(middleware),
    withPermission: middleware.withPermission.bind(middleware),
    batchCheck: middleware.batchCheck.bind(middleware)
  }
}
